package com.springboot.admin.security.service;

import com.springboot.admin.entity.AccountDto;
import com.springboot.admin.mapper.AccountDao;
import com.springboot.admin.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetail implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    AccountDao accountDao;
    @Autowired
    AccountService accountService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AccountDto accountDto = accountDao.getUserByname(username);
        String roleListjoin = accountService.getRoleList(username);

        if (accountDto.getUsername().isEmpty()){
            throw new UsernameNotFoundException("无此用户");
        }

        String pw = passwordEncoder.encode(accountDto.getPassword());

        return new User(accountDto.getUsername(),pw, AuthorityUtils.commaSeparatedStringToAuthorityList(roleListjoin));
    }
}
